package org.rambadger.command.resource;

import com.mongodb.gridfs.GridFS;
import com.mongodb.gridfs.GridFSDBFile;
import com.sun.jersey.api.NotFoundException;
import org.bson.types.ObjectId;

import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;

@Path("/uploads/")
public class DynamicDownloadsResource {
    @Context GridFS gridFS;

//Example
//    @POST @Path("")
//    @Consumes(MULTIPART_FORM_DATA)
//    public Object postFile(@FormDataParam("file") FormDataBodyPart body, @Context UploadHelper helper) {
//        GridFSInputFile file = helper.process(body);
//        file.save();
//        return file.getId().toString();
//    }

    @GET @Path("{fileId: [0-9a-fA-F]{24}}/{filename}")
    public Object getFile(@PathParam("fileId") String fileId,
                          @PathParam("filename") String filename) {
        ObjectId fileObjectId = new ObjectId(fileId);
        GridFSDBFile dbFile = gridFS.findOne(fileObjectId);
        if (dbFile == null) {
            throw new NotFoundException();
        } else {
            return Response.ok().entity(dbFile.getInputStream()).build();
        }
    }
}
